import cheerio from "cheerio";
import request from "request";
import { useragent } from "./index";

const searchReagentByxmolCas = (
  casno: string
  // callback: (data: any) => void
) => {
  return new Promise((resolve, reject) => {
    request(
      {
        url: `https://www.x-mol.com/property?keyWord=${casno}`,
        method: "GET",
        timeout: 3000,
        strictSSL: false,
        headers: {
          "User-Agent": useragent,
        },
      },
      (err, res, body) => {
        if (err) {
          resolve(null);
        } else {
          let $ = cheerio.load(body);
          let reObj: any = null;
          try {
            if (!$(".noresults").length) {
              reObj = {};

              // 获取分子结构图片
              let $imglist: any = $("#main-content .pic-cell-uni img.strImg");
              if ($imglist.length) {
                $imglist.each((index: number, item: any) => {
                  if (index === 0) {
                    reObj.structural = `https://www.x-mol.com${$(item).attr(
                      "src"
                    )}`;
                    return true;
                  }
                  return false;
                });
              }

              let $desc1: any = $(".uniproduct-spec .item-tip");
              if ($desc1.length) {
                $desc1.each((index: number, item: any) => {
                  const titleStr: string = $(item).find("span.dl-tal").text();
                  if (titleStr.indexOf("英文名") >= 0) {
                    reObj.enname = $(item).find(".dd-tal").text();
                  }

                  if (titleStr.indexOf("中文名") >= 0) {
                    reObj.cnname = $(item).find(".dd-tal").text();
                  }

                  if (titleStr.indexOf("分子式") >= 0) {
                    reObj.formula = $(item).find(".dd-tal").text();
                  }

                  if (titleStr.indexOf("分子量") >= 0) {
                    reObj.mw = $(item).find(".dd-tal").text();
                  }
                });
              }

              let $desc2: any = $("table.table-safe tr");
              if ($desc2.length) {
                $desc2.each((index: number, item: any) => {
                  const titleStr: string = $(item).find("th").text();
                  const valueStr: string = $(item).find("td").text().trim();
                  if (titleStr.indexOf("密度") >= 0) {
                    reObj.density = valueStr;
                  }
                  if (titleStr.indexOf("沸点") >= 0) {
                    reObj.bp = valueStr;
                  }
                  if (titleStr.indexOf("熔点") >= 0) {
                    reObj.mp = valueStr;
                  }
                });
              }
            }
          } catch (e) {
            reject(e);
          }
          resolve(reObj);
          // callback(reObj);
        }
      }
    );
  });
};
export default searchReagentByxmolCas;
